package com.ow.dva.module.serverSettings.app;

import com.ow.dva.module.account.service.AccountInfoService;
import com.ow.dva.module.account.service.AccountService;
import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.duty.service.DutyRecordService;
import com.ow.dva.module.duty.service.DutyService;
import com.ow.dva.module.order.entity.Order;
import com.ow.dva.module.order.entity.OrderJson;
import com.ow.dva.module.park.entity.*;
import com.ow.dva.module.park.service.ParkService;
import com.ow.dva.module.park.service.RoadService;
import com.ow.dva.module.passingRecord.entity.PassingRecord;
import com.ow.dva.module.passingRecord.entity.PassingRecordJson;
import com.ow.dva.module.serverSettings.service.ServerSettingsService;
import com.ow.dva.module.terminal.entity.Termina;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ow.dva.util.lockSocket.HandleSocket.*;

@Controller
@RequestMapping("/appServerSettings")
public class AppServerSettingsController {

    /**
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 获取推送的停车场和车位信息
     * @date 2020/3/19
     */

    @RequestMapping(value = "/uploadServer")
    @ResponseBody
    public RT uploadServer(HttpServletRequest request, @RequestBody JsonPark jsonPark) throws IOException {
        if (jsonPark != null) {
            List<Park> parks = jsonPark.getParks();
            List<Parkinglot> parkinglots = jsonPark.getParkinglots();
            List<Road> roads = jsonPark.getRoads();
            List<ParkArea> parkAreas = jsonPark.getParkAreas();
            String terminalCode = jsonPark.getTerminalCode();
            String terminalId = jsonPark.getTerminalId();


            if (parkAreas != null && parkAreas.size()>0){
                saveParkAreas(parkAreas);
            }
            if (parkinglots != null && parkinglots.size()>0){
                saveParkinglot(parkinglots);
            }
            if (parks != null && parks.size()>0){
                savePark(parks,terminalCode,terminalId);
            }
            if (roads != null && roads.size()>0){
                saveRoad(roads);
            }
        }
        return RT.ok();
    }

    /**
     * @param request
     * @param termina
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 获取推送的终端机绑定信息
     * @date 2020/3/26
     */
    @RequestMapping(value = "/postTermina")
    @ResponseBody
    public RT postServer(HttpServletRequest request, @RequestBody Termina termina) throws IOException {
        if (termina != null) {
            saveServerSettings(termina);
        }

        return RT.ok();
    }

    /**
     * @param request
     * @param termina
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 同步删除终端机和服务器的绑定
     * @date 2020/3/30
     */
    @RequestMapping(value = "/deleteTermina")
    @ResponseBody
    public RT deleteTermina(HttpServletRequest request, @RequestBody Termina termina) throws IOException {
        if (termina != null) {
            deleteByTerminaId(termina);
        }

        return RT.ok();
    }

    /**
     * @param request
     * @param termina
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 修改终端机和服务器的绑定状态
     * @date 2020/3/30
     */
    @RequestMapping(value = "/editTermina")
    @ResponseBody
    public RT editTermina(HttpServletRequest request, @RequestBody Termina termina) throws IOException {
        if (termina != null) {
            editByTermianId(termina);
        }

        return RT.ok();
    }

    /**
     * @param request
     * @param orderJson
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 获取推送的订单
     * @date 2020/3/26
     */
    @RequestMapping(value = "/postOrder")
    @ResponseBody
    public RT postOrder(HttpServletRequest request, @RequestBody OrderJson orderJson) throws IOException {
        if (orderJson != null) {
            List<Order> orders = orderJson.getOrders();
            saveOrder(orders);
        }

        return RT.ok();
    }

    /**
     * @param request
     * @param passingRecordJson
     * @return com.ow.dva.module.base.entity.json.RT
     * @author 姜延鹏
     * @Description 获取推送的过车记录
     * @date 2020/3/27
     */
//   @RequestMapping(value = "/passingRecordToServer")
    @ResponseBody
    public RT passingRecordToServer(HttpServletRequest request, @RequestBody PassingRecordJson passingRecordJson) throws IOException {
        if (passingRecordJson != null) {
            List<PassingRecord> passingRecords = passingRecordJson.getPassingRecords();
            savePassingRecord(passingRecords);
        }

        return RT.ok();
    }


    /**
     * @author  姜延鹏
     * @Description  接受上传的图片
     * @param request
     * @date  2020/4/10
     * @return  java.lang.String
     */
    @RequestMapping(value = "/pictureUpload")
    @ResponseBody
    public String pictureUpload(HttpServletRequest request) {

        try {

            Part part = request.getPart("file");

            String fileName = part.getSubmittedFileName();
            InputStream is = part.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            int len;
            // 1K的数据缓冲
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] btImg = outStream.toByteArray();

            if (null != btImg && btImg.length > 0) {
                System.out.println("读取到：" + btImg.length + "字节");
            } else {
                System.out.println("没有从该连接获得内容");
            }

            Date date = new Date();
            String strDateFormat = "yyyyMMdd";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

            String path = ResourceUtils.getURL("classpath:").getPath() + sdf.format(date);
            System.out.println(path);

            File d = new File(path);
            if (!d.exists() && !d.isDirectory()) {
                d.mkdirs();
            }
            File file = new File(path + "\\" + fileName);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(btImg);
            fops.flush();
            fops.close();
            outStream.close();
            is.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
        return "";
    }


    /**
     * @author  姜延鹏
     * @Description  路测二维码值班
     * @param roadId
     * @date  2020/4/10
     * @return  java.lang.String
     */
    @RequestMapping(value = "/dutyCode",produces = "application/json; charset=utf-8")
    @ResponseBody
    public RT qrCode(String roadId) {

        RT duty = serverSettingsService.getDutyAccount(roadId);
        if (duty.getSuccess() == true){
            return RT.ok("值班人信息",duty.getData());
        }else {
            return RT.error(1,duty.getMessage());
        }
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    //
//    /**
//     * 登录
//     * @param account （userword，password）
//     * @return 成功状态
//     */
//    @RequestMapping(value="/login")
//    @ResponseBody
//    public RT login(Account account, HttpSession session) throws Exception {
//
//        String msg = "登录成功";
//        if(!ValNameAndPassWord(account).getSuccess()){
//            return ValNameAndPassWord(account);
//        }
//        //获取当前会话主体
//        Subject subject = SecurityUtils.getSubject();
//
//        //获取token
//        UsernamePasswordToken token = new UsernamePasswordToken(account.getUserName(), account.getPassword());
//
//        //是否记住密码
//        //token.setRememberMe(true);
//
//        try {
//            //登录
//            subject.login(token);
//
//            //如果登录成功
//            if (subject.isAuthenticated()) {
//
//                Account a = accountService.findByUserName(account.getUserName());
//                AccountInfo ua =new AccountInfo();
//                ua.setAccountId(a.getId());
//
//                ShiroAccount shiroAccount = (ShiroAccount) subject.getPrincipal();
//
//                Account dba = shiroAccount.getAccount();
//
//                if("park,".equals(dba.getType())) {
//                    session.setAttribute(UserConstant.ACCOUNT,dba);
//                    // 获取详细信息
//                    AccountInfo accountInfo = accountInfoService.findByAccountId(dba.getId());
//                    session.setAttribute(UserConstant.ACCOUNT_INFO, accountInfo);
//                    return  RT.ok();
//                } else {
//                    msg = "账号类型错误！";
//                    return  RT.error(5, msg);
//                }
//            }
//        } catch (IncorrectCredentialsException e) {
//            msg = "登录密码错误！";
//            System.out.println();
//            return  RT.error(11,msg);
//        } catch (ExcessiveAttemptsException e) {
//            msg = "登录失败次数过多！";
//            return  RT.error(12,msg);
//        } catch (LockedAccountException e) {
//            msg = "帐号已被锁定！";
//            return  RT.error(13,msg);
//        } catch (DisabledAccountException e) {
//            msg = "帐号已被禁用！";
//            return  RT.error(14,msg);
//        } catch (ExpiredCredentialsException e) {
//            msg = "帐号已过期！";
//            return  RT.error(15,msg);
//        } catch (UnknownAccountException e) {
//            msg = "帐号不存在！";
//            return  RT.error(16,msg);
//        } catch (UnauthorizedException e) {
//            msg = "您没有得到相应的授权！";
//            return  RT.error(17,msg);
//        }
//        return RT.ok(1);
//    }
//
//    /**
//     * 验证传过来的参数有没有用户名或者密码
//     * @param account 实体对象
//     * @return 提示信息
//     */
//    public RT ValNameAndPassWord(Account account){
//        if (StringUtils.isBlank(account.getUserName())) {
//            return RT.error(3,"用户名不能为空！");
//        }
//        if (StringUtils.isBlank(account.getPassword())) {
//            return RT.error(4,"密码不能为空！");
//        }
//        return RT.ok();
//    }
//
//
//    /**
//     * 注册用户
//     * @param account 带id的account对象
//     * @return 成功状态
//     */
//    @RequestMapping(value="/register")
//    @ResponseBody
//    public RT register(Account account) {
//        Account list =accountService.findByUserName(account.getUserName());
//        if(list!=null){
//            return RT.error(2,"手机号已注册！");
//        }else {
//            try {
//                Account a = saveAccount(account);
//                AccountInfo accountInfo = accountInfoService.findByAccountId(a.getId());
//                return RT.ok(accountInfo);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return RT.error(1, "保存失败！");
//            }
//        }
//    }
//
//
//    /**
//     * 保存用户到用户表和account表
//     */
//    public Account saveAccount(Account account){
//        try {
//            account.setId(UUIDFactory.getStringId());
//            account.setType("park,");
//            account.setStatus(1);
//            account.setPassword(md5("123456"));
//            AccountInfo accountInfo = new AccountInfo();
//            accountInfo.setId(UUIDFactory.getStringId());
//            accountInfo.setAccountId(account.getId());
//            accountInfo.setName(account.getUserName());
//            accountInfo.setPhone(account.getUserName());
//            accountInfo.setCreateTime(new Date());
//            accountInfo.setCardVerify(0);
//            accountService.save(account);
//            accountInfoService.save(accountInfo);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return account;
//    }
//
//    /**
//     * 找回密码
//     * @param userName,password,code  用户名，新密码，验证码
//     * @return 成功状态
//     */
//    @RequestMapping(value="/findBackPassword")
//    @ResponseBody
//    public RT findBackPassword(String userName, String password, String code) {
//        Account account =accountService.findByUserName(userName);
//        account.setPassword(password);
//        try {
//            accountService.updateById(account);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return RT.ok("重置密码成功！");
//    }
//
    @Resource
    private AccountService accountService;
    @Resource
    private AccountInfoService accountInfoService;
    @Resource
    private DutyService dutyService;
    @Resource
    private DutyRecordService dutyRecordService;
    @Resource
    private ParkService parkService;
    @Resource
    private RoadService roadService;
    @Resource
    private ServerSettingsService serverSettingsService;

}
